package com.example.autopia.model.Repositories

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Item.Parking
import com.example.autopia.model.Item.Place
import com.example.autopia.model.Item.User
import com.example.autopia.utilities.KEY_BD_PARKING
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class ParkingRepository {
    private val database = FirebaseDatabase.getInstance()
    private var reference = database.getReference(KEY_BD_PARKING)

    fun addParking(parking: Parking): Boolean {
        var status = false
        val newItem = reference.push()
        parking.id = newItem.key ?: ""
        newItem.setValue(parking)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changeAllPlacesCount(parkingId: String, newCount: Int): Boolean {
        var status = false
        reference.child(parkingId).child("allPlaces").setValue(newCount)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addFreePlacesCount(parkingId: String): Boolean {
        var status = false
        reference.child(parkingId).child("freeSpaces").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newData = task.result.value
                if (newData != null) {
                    // Проверьте, что данные не пусты, а затем увеличьте значение likes
                    val currentFreePlaces = newData as Long
                    val updatedPlaces = currentFreePlaces + 1
                    reference.child(parkingId).child("freeSpaces").setValue(updatedPlaces)
                    status = true
                }
            } else {
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }

    fun removeFreePlacesCount(parkingId: String): Boolean {
        var status = false
        reference.child(parkingId).child("freeSpaces").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newData = task.result.value
                if (newData != null) {
                    // Проверьте, что данные не пусты, а затем увеличьте значение likes
                    val currentFreePlaces = newData as Long
                    val updatedPlaces = currentFreePlaces - 1
                    reference.child(parkingId).child("freeSpaces").setValue(updatedPlaces)
                    status = true
                }
            } else {
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }

    fun changePrice(parkingId: String, newPrice: Int): Boolean {
        var status = false
        reference.child(parkingId).child("price").setValue(newPrice)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun changePlace(parkingId: String, placeId: String, place: Place): Boolean {
        var status = false
        reference.child(parkingId).child("placeList")
            .addListenerForSingleValueEvent(object : ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    for (itemSnapshot in snapshot.children) {
                        if (itemSnapshot.child("id").value.toString() == placeId) {
                            itemSnapshot.key?.let {
                                reference.child(parkingId).child("placeList")
                                    .child(it).setValue(place)
                            }
                        }
                    }
                }
                override fun onCancelled(error: DatabaseError) {
                    Log.d("Yatoro",error.toString())
                }
            })
        return status
    }

    fun getAllItems(): MutableLiveData<ArrayList<Parking>> {
        val itemsList = ArrayList<Parking>()
        val result = MutableLiveData<ArrayList<Parking>>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children) {
                    val id = itemSnapshot.child("id").value.toString()
                    val name = itemSnapshot.child("name").value.toString()
                    val address = itemSnapshot.child("address").value.toString()
                    val price = itemSnapshot.child("price").value.toString().toInt()
                    val description = itemSnapshot.child("description").value.toString()
                    val allPlaces = itemSnapshot.child("allPlaces").value.toString().toInt()
                    val freePlaces = itemSnapshot.child("freePlaces").value.toString().toInt()
                    val placeList = ArrayList<Place>()
                    for (places in itemSnapshot.child("placeList").children) {
                        val id = places.child("id").value.toString()
                        val status = places.child("status").value.toString().toInt()
                        val userId = places.child("userId").value.toString()
                        val car = places.child("car").getValue(Car::class.java)
                        val place = Place(id, status, car, userId)
                        placeList.add(place)
                    }
                    val parking = Parking(
                        id,
                        name,
                        address,
                        price,
                        description,
                        allPlaces,
                        freePlaces,
                        placeList
                    )
                    itemsList.add(parking)
                }
                result.value = itemsList
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro", "Ошибка в Parking")
            }
        })
        return result
    }

    fun getParkingById(id: String): MutableLiveData<Parking> {
        val parking: MutableLiveData<Parking> = MutableLiveData()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val currentSnapshot = dataSnapshot.child(id)
                if (currentSnapshot.exists()) {
                    val id = currentSnapshot.child("id").value.toString()
                    val name = currentSnapshot.child("name").value.toString()
                    val address = currentSnapshot.child("address").value.toString()
                    val price = currentSnapshot.child("price").value.toString().toInt()
                    val description = currentSnapshot.child("description").value.toString()
                    val allPlaces = currentSnapshot.child("allPlaces").value.toString().toInt()
                    val freePlaces = currentSnapshot.child("freePlaces").value.toString().toInt()
                    val placeList = ArrayList<Place>()
                    for (places in currentSnapshot.child("placeList").children) {
                        val id = places.child("id").value.toString()
                        val status = places.child("status").value.toString().toInt()
                        val userId = places.child("userId").value.toString()
                        val car = places.child("car").getValue(Car::class.java)
                        val place = Place(id, status, car, userId)
                        placeList.add(place)
                    }
                    parking.value = Parking(
                        id,
                        name,
                        address,
                        price,
                        description,
                        allPlaces,
                        freePlaces,
                        placeList
                    )
                } else {
                }
            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Обработка ошибки
            }
        })
        return parking
    }
    fun updaterPlaces(id: String): MutableLiveData<Parking> {
        val parking: MutableLiveData<Parking> = MutableLiveData()
        reference.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val currentSnapshot = dataSnapshot.child(id)
                if (currentSnapshot.exists()) {
                    val id = currentSnapshot.child("id").value.toString()
                    val name = currentSnapshot.child("name").value.toString()
                    val address = currentSnapshot.child("address").value.toString()
                    val price = currentSnapshot.child("price").value.toString().toInt()
                    val description = currentSnapshot.child("description").value.toString()
                    val allPlaces = currentSnapshot.child("allPlaces").value.toString().toInt()
                    val freePlaces = currentSnapshot.child("freePlaces").value.toString().toInt()
                    val placeList = ArrayList<Place>()
                    for (places in currentSnapshot.child("placeList").children) {
                        val id = places.child("id").value.toString()
                        val status = places.child("status").value.toString().toInt()
                        val userId = places.child("userId").value.toString()
                        val car = places.child("car").getValue(Car::class.java)
                        val place = Place(id, status, car, userId)
                        placeList.add(place)
                    }
                    parking.value = Parking(
                        id,
                        name,
                        address,
                        price,
                        description,
                        allPlaces,
                        freePlaces,
                        placeList
                    )
                    Log.d("Yatoro", parking.toString())
                } else {
                }
            }
            override fun onCancelled(databaseError: DatabaseError) {
                // Обработка ошибки
            }
        })
        return parking
    }
}